/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.garagesale.user.web.action;

import com.garagesale.data.DBAccess;
import com.garagesale.data.Item;
import com.garagesale.user.web.form.ListItemsForm;
import java.math.BigDecimal;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author christophe
 */
public class ListItems extends org.apache.struts.action.Action
{

    /* forward name="success" path="" */
    private static final String SUCCESS = "success";

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {

        ListItemsForm listForm = (ListItemsForm) form;

        // retrieve all available categories
        listForm.setCategories(DBAccess.getInstance().getAllCategories());

        BigDecimal lowPrice = null != emptyToNull(listForm.getLowerPriceFilter()) ? BigDecimal.valueOf(Double.valueOf(listForm.getLowerPriceFilter())) : null;
        BigDecimal highPrice = null != emptyToNull(listForm.getUpperPriceFilter()) ? BigDecimal.valueOf(Double.valueOf(listForm.getUpperPriceFilter())) : null;
        Integer categoryFilter = null != emptyToNull(listForm.getCategoryFilter()) ? Integer.valueOf(listForm.getCategoryFilter()) : null;



        List<Item> items = DBAccess.getInstance().seachItems(emptyToNull(listForm.getNameFilter()), categoryFilter, emptyToNull(listForm.getDescriptionFilter()), lowPrice, highPrice, true);

        listForm.setItems(items);

        return mapping.findForward("list");
    }

    private String emptyToNull(String value)
    {
        if (null == value || value.trim().length() == 0)
        {
            return null;
        }

        return value;
    }
}
